Install folium¶

In [5]:
pip install folium
Requirement already satisfied: folium in c:\python\lib\site-packages (0.14.0)
Requirement already satisfied: requests in c:\python\lib\site-packages (from folium) (2.28.2)
Requirement already satisfied: numpy in c:\python\lib\site-packages (from folium) (1.23.5)
Requirement already satisfied: branca>=0.6.0 in c:\python\lib\site-packages (from folium) (0.6.0)
Requirement already satisfied: jinja2>=2.9 in c:\python\lib\site-packages (from folium) (3.1.2)
Requirement already satisfied: MarkupSafe>=2.0 in c:\python\lib\site-packages (from jinja2>=2.9->folium) (2.1.2)
Requirement already satisfied: idna<4,>=2.5 in c:\python\lib\site-packages (from requests->folium) (3.4)
Requirement already satisfied: charset-normalizer<4,>=2 in c:\python\lib\site-packages (from requests->folium) (2.1.1)
Requirement already satisfied: certifi>=2017.4.17 in c:\python\lib\site-packages (from requests->folium) (2022.12.7)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in c:\python\lib\site-packages (from requests->folium) (1.26.14)
Note: you may need to restart the kernel to use updated packages.
[notice] A new release of pip available: 22.3.1 -> 23.0.1
[notice] To update, run: python.exe -m pip install --upgrade pip
In [6]:
import folium

render a location[chennai] in map¶

In [7]:
m = folium.Map(location=[13.067439, 80.237617], zoom_start=13)

display¶

In [8]:
m.get_center()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[8], line 1
----> 1 m.get_center()

AttributeError: 'Map' object has no attribute 'get_center'
In [3]:
m
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[3], line 1
----> 1 m

NameError: name 'm' is not defined

save rendered map in html¶

In [4]:
m.save("index.html")
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[4], line 1
----> 1 m.save("index.html")

NameError: name 'm' is not defined

markers¶

tiles = background map, tooltip = add custom text popup = marker location tooltip = hover message

In [30]:
m = folium.Map(location=[13.067439, 80.237617], zoom_start=12,tiles="Stamen Terrain")
tooltip = "Click me!"
folium.Marker(
    [13.077784, 80.260728], popup="<i>egmore station</i>", tooltip=tooltip
).add_to(m)
folium.Marker(
    [13.014112, 80.244735], popup="<b>kotturpuram playground</b>", tooltip=tooltip
).add_to(m)
Out[30]:
<folium.map.Marker at 0x269251f3ca0>
In [31]:
m
Out[31]:
Make this Notebook Trusted to load map: File -> Trust Notebook

marker icon¶

In [4]:
m = folium.Map(location=[13.067439, 80.237617], zoom_start=12,tiles="Stamen Terrain")
tooltip = "Click me!"
folium.Marker(
    [13.077784, 80.260728], popup="<i>egmore station</i>", icon=folium.Icon(color="green", icon="info-sign")
).add_to(m)
folium.Marker(
    [13.014112, 80.244735], popup="<b>kotturpuram playground</b>", icon=folium.Icon(color="red", icon="info-sign")
).add_to(m)

m
Out[4]:
Make this Notebook Trusted to load map: File -> Trust Notebook

add custom icons

In [16]:
import base64
In [38]:
m = folium.Map(location=[13.067439, 80.237617], zoom_start=12,tiles="Stamen Terrain")
tooltip = "Click me!"

folium.Marker(
    [13.09, 80.27], popup="<i>egmore station</i>", angle=180, icon=folium.Icon(color="blue",icon="charging-station", prefix='fa')
).add_to(m)
folium.Marker(
    [13.014112, 80.244735], popup="<b>kotturpuram playground</b>",icon=folium.Icon(color="red", icon="info-sign")
).add_to(m)

m
Out[38]:
Make this Notebook Trusted to load map: File -> Trust Notebook

circle marker¶

In [35]:
m = folium.Map(location=[45.5236, -122.6750], tiles="Stamen Toner", zoom_start=13)

folium.Circle(
    radius=100,
    location=[45.5244, -122.6699],
    popup="The Waterfront",
    color="crimson",
    fill=False,
).add_to(m)

folium.CircleMarker(
    location=[45.5215, -122.6261],
    radius=50,
    popup="Laurelhurst Park",
    color="#3186cc",
    fill=True,
    fill_color="#3186cc",
).add_to(m)
Out[35]:
<folium.vector_layers.CircleMarker at 0x269266684f0>
In [36]:
m
Out[36]:
Make this Notebook Trusted to load map: File -> Trust Notebook

enable latlong on click¶

In [38]:
m = folium.Map(location=[46.1991, -122.1889], tiles="Stamen Terrain", zoom_start=13)

m.add_child(folium.LatLngPopup())

m
Out[38]:
Make this Notebook Trusted to load map: File -> Trust Notebook

on the fly marker addition¶

In [39]:
m = folium.Map(location=[46.8527, -121.7649], tiles="Stamen Terrain", zoom_start=13)

folium.Marker([46.8354, -121.7325], popup="Camp Muir").add_to(m)

m.add_child(folium.ClickForMarker(popup="Waypoint"))


m
Out[39]:
Make this Notebook Trusted to load map: File -> Trust Notebook

Polyline¶

In [40]:
m = folium.Map(location=[-71.38, -73.9], zoom_start=11)

trail_coordinates = [
    (-71.351871840295871, -73.655963711222626),
    (-71.374144382613707, -73.719861619751498),
    (-71.391042575973145, -73.784922248007007),
    (-71.400964450973134, -73.851042243124397),
    (-71.402411391077322, -74.050048183880477),
]


folium.PolyLine(trail_coordinates, tooltip="Coast").add_to(m)

m
Out[40]:
Make this Notebook Trusted to load map: File -> Trust Notebook

Vincent/Vega and Altair/VegaLite Markers[load from html]¶

In [41]:
import json

import requests

url = (
    "https://raw.githubusercontent.com/python-visualization/folium/main/examples/data"
)
vis1 = json.loads(requests.get(f"{url}/vis1.json").text)
vis2 = json.loads(requests.get(f"{url}/vis2.json").text)
vis3 = json.loads(requests.get(f"{url}/vis3.json").text)
In [42]:
m = folium.Map(location=[46.3014, -123.7390], zoom_start=7, tiles="Stamen Terrain")

folium.Marker(
    location=[47.3489, -124.708],
    popup=folium.Popup(max_width=450).add_child(
        folium.Vega(vis1, width=450, height=250)
    ),
).add_to(m)

folium.Marker(
    location=[44.639, -124.5339],
    popup=folium.Popup(max_width=450).add_child(
        folium.Vega(vis2, width=450, height=250)
    ),
).add_to(m)

folium.Marker(
    location=[46.216, -124.1280],
    popup=folium.Popup(max_width=450).add_child(
        folium.Vega(vis3, width=450, height=250)
    ),
).add_to(m)


m
Out[42]:
Make this Notebook Trusted to load map: File -> Trust Notebook

Overlays [GeoJSON/TopoJSON Overlays]¶

In [43]:
url = (
    "https://raw.githubusercontent.com/python-visualization/folium/main/examples/data"
)
antarctic_ice_edge = f"{url}/antarctic_ice_edge.json"
antarctic_ice_shelf_topo = f"{url}/antarctic_ice_shelf_topo.json"


m = folium.Map(
    location=[-59.1759, -11.6016],
    tiles="cartodbpositron",
    zoom_start=2,
)

folium.GeoJson(antarctic_ice_edge, name="geojson").add_to(m)

folium.TopoJson(
    json.loads(requests.get(antarctic_ice_shelf_topo).text),
    "objects.antarctic_ice_shelf",
    name="topojson",
).add_to(m)

folium.LayerControl().add_to(m)


m
Out[43]:
Make this Notebook Trusted to load map: File -> Trust Notebook

Choropleth maps¶

Choropleth can be easily created by binding the data between Pandas DataFrames/Series and Geo/TopoJSON geometries. Color Brewer sequential color schemes are built-in to the library, and can be passed to quickly visualize different combinations

In [44]:
import pandas as pd

url = (
    "https://raw.githubusercontent.com/python-visualization/folium/main/examples/data"
)
state_geo = f"{url}/us-states.json"
state_unemployment = f"{url}/US_Unemployment_Oct2012.csv"
state_data = pd.read_csv(state_unemployment)

m = folium.Map(location=[48, -102], zoom_start=3)

folium.Choropleth(
    geo_data=state_geo,
    name="choropleth",
    data=state_data,
    columns=["State", "Unemployment"],
    key_on="feature.id",
    fill_color="YlGn",
    fill_opacity=0.7,
    line_opacity=0.2,
    legend_name="Unemployment Rate (%)",
).add_to(m)

folium.LayerControl().add_to(m)

m
Out[44]:
Make this Notebook Trusted to load map: File -> Trust Notebook

passing own legend

In [45]:
bins = list(state_data["Unemployment"].quantile([0, 0.25, 0.5, 0.75, 1]))

m = folium.Map(location=[48, -102], zoom_start=3)

folium.Choropleth(
    geo_data=state_geo,
    data=state_data,
    columns=["State", "Unemployment"],
    key_on="feature.id",
    fill_color="BuPu",
    fill_opacity=0.7,
    line_opacity=0.5,
    legend_name="Unemployment Rate (%)",
    bins=bins,
    reset=True,
).add_to(m)

m
Out[45]:
Make this Notebook Trusted to load map: File -> Trust Notebook

Styling function¶

GeoJson and TopoJson features accepts style_function to allow for further custimization of the map. Take a look at the use examples below.

In [46]:
import branca

url = (
    "https://raw.githubusercontent.com/python-visualization/folium/main/examples/data"
)
county_data = f"{url}/us_county_data.csv"
county_geo = f"{url}/us_counties_20m_topo.json"


df = pd.read_csv(county_data, na_values=[" "])

colorscale = branca.colormap.linear.YlOrRd_09.scale(0, 50e3)
employed_series = df.set_index("FIPS_Code")["Employed_2011"]


def style_function(feature):
    employed = employed_series.get(int(feature["id"][-5:]), None)
    return {
        "fillOpacity": 0.5,
        "weight": 0,
        "fillColor": "#black" if employed is None else colorscale(employed),
    }


m = folium.Map(location=[48, -102], tiles="cartodbpositron", zoom_start=3)

folium.TopoJson(
    json.loads(requests.get(county_geo).text),
    "objects.us_counties_20m",
    style_function=style_function,
).add_to(m)


m
Out[46]:
Make this Notebook Trusted to load map: File -> Trust Notebook
In [47]:
colorscale = branca.colormap.linear.YlGnBu_09.scale(0, 30)

employed_series = df.set_index("FIPS_Code")["Unemployment_rate_2011"]


def style_function(feature):
    employed = employed_series.get(int(feature["id"][-5:]), None)
    return {
        "fillOpacity": 0.5,
        "weight": 0,
        "fillColor": "#black" if employed is None else colorscale(employed),
    }


m = folium.Map(location=[48, -102], tiles="cartodbpositron", zoom_start=3)

folium.TopoJson(
    json.loads(requests.get(county_geo).text),
    "objects.us_counties_20m",
    style_function=style_function,
).add_to(m)


m
Out[47]:
Make this Notebook Trusted to load map: File -> Trust Notebook
In [48]:
colorscale = branca.colormap.linear.PuRd_09.scale(0, 100000)

employed_series = df.set_index("FIPS_Code")["Median_Household_Income_2011"].dropna()


def style_function(feature):
    employed = employed_series.get(int(feature["id"][-5:]), None)
    return {
        "fillOpacity": 0.5,
        "weight": 0,
        "fillColor": "#black" if employed is None else colorscale(employed),
    }


m = folium.Map(location=[48, -102], tiles="cartodbpositron", zoom_start=3)

folium.TopoJson(
    json.loads(requests.get(county_geo).text),
    "objects.us_counties_20m",
    style_function=style_function,
).add_to(m)


m
Out[48]:
Make this Notebook Trusted to load map: File -> Trust Notebook
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]: